package com.taobao.sinan.dal.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.taobao.sinan.dal.App;
import com.taobao.sinan.dal.DataSource;
import com.taobao.sinan.dal.Table;

public class DataSourceManager {
	private static final Map<String, DataSourceManager> instances = new HashMap<String, DataSourceManager>();
	private List<DataSource> dataSources = new ArrayList<DataSource>();

	private DataSourceManager() {
		
	}

	public static synchronized DataSourceManager getInstance(App app) {
		DataSourceManager instance = instances.get(app.getName());
		if (instance == null) {
			instance = new DataSourceManager();
			instances.put(app.getName(), instance);
		}

		return instance;
	}

	public Collection<DataSource> getAllDataSource() {
		return dataSources;
	}
	
	public void addDataSource(DataSource ds) {
		dataSources.add(ds);
	}

	public DataSource getDataSourceByTable(Table table) {
		for (DataSource ds : dataSources) {
			if (ds.getName().equals(table.getDbname()) && ds.getTables().contains(table.getTbname())) {
				return ds;
			}
		}

		return null;
	}
}
